package com.vrv.vap.server.service.impl;

import com.vrv.vap.domain.LoginUser;
import com.vrv.vap.server.service.PermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author wh1107066
 * @date 2021/6/21 15:13
 */
@Component("permissionService")
public class PermissionServiceImpl implements PermissionService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 获取登陆的用户名
     */
    public static String getUsername(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal instanceof org.springframework.security.core.userdetails.User) {
            username = ((org.springframework.security.core.userdetails.User) principal).getUsername();
        } else if(principal instanceof LoginUser){
            username = ((LoginUser) principal).getUsername();
        } else if (principal instanceof String) {
            username = (String) principal;
        } else {
            throw  new RuntimeException("转化失败!!1");
        }
        return username;
    }

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        logger.info("请求uri:{}", request.getRequestURI());
        boolean hasPermission = false;
        logger.info(String.format("principal is %s", principal));

        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            //超级管理员admin不需认证
            String username = getUsername(authentication);
            if ("admin".equalsIgnoreCase(username)) {
                hasPermission = true;
            } else {
                // 读取用户所拥有权限的所有URL, 现在放的是role， 需要把所有的role转化成urls，才能够进行判断
                List<SimpleGrantedAuthority> list = (List<SimpleGrantedAuthority>)authentication.getAuthorities();
                for (SimpleGrantedAuthority authority : list) {
                    // TODO 自己实现相关业务需求， 或者把所有的链接放入到权限中
    //                if (antPathMatcher.match(url, request.getRequestURI())) {
    //                    hasPermission = true;
    //                    break;
    //                }
                    logger.info("角色信息:{}" ,authority);
                }
            }
        }
        return hasPermission;
    }

}
